package com.dream.inspect.modules.sys.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dream.inspect.common.utils.PageUtils;
import com.dream.inspect.common.utils.Query;
import com.dream.inspect.modules.dream.pojo.AuditApplyFormMap;
import com.dream.inspect.modules.sys.dao.AuditApplyDao;
import com.dream.inspect.modules.sys.dao.SysUserDao;
import com.dream.inspect.modules.sys.dao.SysUserRoleDao;
import com.dream.inspect.modules.sys.entity.AuditApplyEntity;
import com.dream.inspect.modules.sys.entity.SysUserEntity;
import com.dream.inspect.modules.sys.entity.SysUserRoleEntity;
import com.dream.inspect.modules.sys.service.AuditApplyService;

@Service("auditApplyService")
public class AuditApplyServiceImpl extends ServiceImpl<AuditApplyDao, AuditApplyEntity> implements AuditApplyService {

	@Resource
	private AuditApplyDao auditApplyDao;
	@Resource
	private SysUserRoleDao sysUserRoleDao;
	@Resource
	private SysUserDao sysUserDao;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void apply(Map<String, Object> params) {
		String[] ids = (params.get("ids") + "").split(",");
		Long auditId = Long.parseLong(params.get("auditId")+"");
		Date now = new Date();
		for(String id : ids){
			AuditApplyEntity entity = new AuditApplyEntity();
			AuditApplyEntity temp = new AuditApplyEntity();
			entity.setId(Long.parseLong(id));
			temp = auditApplyDao.selectOne(entity);
			entity.setAuditId(auditId);
			entity.setAuditTime(now);
			// 审核表改变
			entity.setAuditFlag("1");
			auditApplyDao.updateById(entity);
			
			// 将申请人的role改变;
			Map<String, Object> where = new HashMap<String, Object>();
			where.put("user_id", temp.getUserId());
			sysUserRoleDao.deleteByMap(where);
			SysUserRoleEntity userRole = new SysUserRoleEntity();
			userRole.setRoleId(temp.getRoleId());
			userRole.setUserId(temp.getUserId());
			sysUserRoleDao.insert(userRole);
			// 将申请人的账号激活
			SysUserEntity user = new SysUserEntity();
			user.setUserId(temp.getUserId());
			user.setUpdateTime(now);
			user.setStatus(1);
			sysUserDao.updateById(user);
		}
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params){
		Page<AuditApplyFormMap> page = selectThisPage(new Query<AuditApplyFormMap>(params),
                new Query<AuditApplyFormMap>(params).getPage()
        );

        return new PageUtils(page);
	}
	
	private Page<AuditApplyFormMap> selectThisPage(Map<String ,Object> map, Page<AuditApplyFormMap> page) {
        page.setRecords(auditApplyDao.findList(map,page));
        return page;
    }

}
